package com.pos.clothes.controller;

import com.pos.clothes.pojo.User;
import com.pos.clothes.service.UserService;
import com.pos.clothes.util.JsonData;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HomeIndexController {

    @Autowired
    private UserService service;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @ResponseBody
    public Object defaultLogin() {
        return JsonData.buildError("未登录，跳到首页");
    }


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(@RequestParam("gonghao") String gonghao, @RequestParam("password") String password) {
        // 从SecurityUtils里边创建一个 subject
//        User user = new User();
//        user.setPassword(password);
//        user.setUser_name(username);
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(gonghao, password);
        // 执行认证登陆
        try {
//            subject.getSession().setAttribute("user", user);
            subject.login(token);
        } catch (UnknownAccountException uae) {
            return JsonData.buildError("未知账户");
        } catch (IncorrectCredentialsException ice) {
            return JsonData.buildError("密码不正确");
        } catch (LockedAccountException lae) {
            return JsonData.buildError("账户已锁定");
        } catch (ExcessiveAttemptsException eae) {
            return JsonData.buildError("用户名或密码错误次数过多");
        } catch (AuthenticationException ae) {
            return JsonData.buildError("用户名或密码不正确！") ;
        }
        if (subject.isAuthenticated()) {
            return JsonData.buildSuccess(service.getByUsername(gonghao),"登录成功");
//            return JsonData.buildSuccess(200,"登录成功");
        } else {
            token.clear();
            return JsonData.buildError("登录失败");
        }
    }

}
